package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IScoreManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IDbQualificationManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.system.service.IDbIdentityManagementService;

import javax.validation.Validator;

import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

/**
 * 四级联考递补资格审查Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class DbQualificationManagementServiceImpl implements IDbQualificationManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(DbQualificationManagementServiceImpl.class);

    @Autowired
    private DbQualificationManagementMapper dbQualificationManagementMapper;
    
    @Autowired
    protected Validator validator;

    @Autowired
    private IDbIdentityManagementService dbIdentityManagementService;

    @Autowired
    private ResultManagementMapper resultManagementMapper;

    @Autowired
    private DbPhysicalManagementMapper dbPhysicalManagementMapper;

    @Autowired
    private DbIdentityManagementMapper dbIdentityManagementMapper;

    @Autowired
    private IScoreManagementService scoreManagementService;

    @Autowired
    private QualificationManagementMapper qualificationManagementMapper;

    @Autowired
    private IdentityManagementMapper identityManagementMapper;

    @Autowired
    private PhysicalManagementMapper physicalManagementMapper;
    /**
     * 查询四级联考递补资格审查
     * 
     * @param id 四级联考递补资格审查主键
     * @return 四级联考递补资格审查
     */
    @Override
    public DbQualificationManagement selectDbQualificationManagementById(Long id)
    {
        return dbQualificationManagementMapper.selectDbQualificationManagementById(id);
    }

    /**
     * 查询四级联考递补资格审查列表
     * 
     * @param dbQualificationManagement 四级联考递补资格审查
     * @return 四级联考递补资格审查
     */
    @Override
    public List<DbQualificationManagement> selectDbQualificationManagementList(DbQualificationManagement dbQualificationManagement)
    {
        return dbQualificationManagementMapper.selectDbQualificationManagementList(dbQualificationManagement);
    }

    /**
     * 新增四级联考递补资格审查
     * 
     * @param dbQualificationManagement 四级联考递补资格审查
     * @return 结果
     */
    @Override
    public int insertDbQualificationManagement(DbQualificationManagement dbQualificationManagement)
    {
        return dbQualificationManagementMapper.insertDbQualificationManagement(dbQualificationManagement);
    }

    /**
     * 修改四级联考递补资格审查
     * 
     * @param dbQualificationManagement 四级联考递补资格审查
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDbQualificationManagement(DbQualificationManagement dbQualificationManagement)
    {
        // 获取原有数据
        DbQualificationManagement originalData = selectDbQualificationManagementById(dbQualificationManagement.getId());
        
        // 执行更新操作
        int rows = dbQualificationManagementMapper.updateDbQualificationManagement(dbQualificationManagement);
        
        // 如果更新成功，且资格审查结果从非"通过"变为"通过"，则自动流转到递补身份验证模块
        if (rows > 0 && "通过".equals(dbQualificationManagement.getQualificationReviewResult()) 
            && (originalData == null || !"通过".equals(originalData.getQualificationReviewResult())))
        {
            log.info("考生{}（身份证号：{}）递补资格审查结果修改为\"通过\"，自动流转到递补身份验证模块", 
                     dbQualificationManagement.getName(), dbQualificationManagement.getIdCard());
            
            try
            {
                // 创建只包含当前考生的列表
                List<DbQualificationManagement> qualifiedList = new java.util.ArrayList<>();
                qualifiedList.add(dbQualificationManagement);
                
                // 调用递补身份验证服务，将考生添加到递补身份验证名单
                dbIdentityManagementService.insertDbIdentityListFromDbQualification(qualifiedList, "系统自动");
                log.info("考生{}（身份证号：{}）成功流转到递补身份验证模块", 
                         dbQualificationManagement.getName(), dbQualificationManagement.getIdCard());
            }
            catch (Exception e)
            {
                log.error("考生流转到递补身份验证模块失败", e);
                // 这里不抛出异常，确保即使流转失败，更新操作仍然成功
            }
        }
        
        return rows;
    }

    /**
     * 批量删除四级联考递补资格审查
     * 
     * @param ids 需要删除的四级联考递补资格审查主键
     * @return 结果
     */
    @Override
    public int deleteDbQualificationManagementByIds(Long[] ids)
    {
        return dbQualificationManagementMapper.deleteDbQualificationManagementByIds(ids);
    }

    /**
     * 删除四级联考递补资格审查信息
     * 
     * @param id 四级联考递补资格审查主键
     * @return 结果
     */
    @Override
    public int deleteDbQualificationManagementById(Long id)
    {
        return dbQualificationManagementMapper.deleteDbQualificationManagementById(id);
    }

    /**
     * 导入四级联考递补资格审查数据
     * 
     * @param dbQualificationList 递补资格审查数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importDbQualificationData(List<DbQualificationManagement> dbQualificationList, boolean updateSupport, String operName)
    {

        // 终审结果表
        resultManagementMapper.deleteAllResultManagement();

        // 递补体能测试表
        dbPhysicalManagementMapper.deleteAllDbPhysicalManagement();

        // 递补身份验证表
        dbIdentityManagementMapper.deleteAllIdentityManagement();

        // 递补资格审查表
        dbQualificationManagementMapper.deleteAllDbQualificationManagement();


        if (StringUtils.isNull(dbQualificationList) || dbQualificationList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (DbQualificationManagement dbQualification : dbQualificationList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                DbQualificationManagement existDbQualification = new DbQualificationManagement();
                if (StringUtils.isNotEmpty(dbQualification.getExamNumber()))
                {
                    existDbQualification.setExamNumber(dbQualification.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(dbQualification.getIdCard()))
                {
                    existDbQualification.setIdCard(dbQualification.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<DbQualificationManagement> existList = dbQualificationManagementMapper.selectDbQualificationManagementList(existDbQualification);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
                    // 如果不存在，执行插入操作
                    dbQualificationManagementMapper.insertDbQualificationManagement(dbQualification);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbQualification.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    dbQualification.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    dbQualificationManagementMapper.updateDbQualificationManagement(dbQualification);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbQualification.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + dbQualification.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + dbQualification.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 从成绩合格名单生成并插入递补资格审查名单
     * 
     * @param scoreList 符合条件的成绩合格名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDbQualificationListFromScore(List<ScoreManagement> scoreList, String operName)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有递补资格审查名单数据
        DbQualificationManagement clearCriteria = new DbQualificationManagement();
        List<DbQualificationManagement> existingList = dbQualificationManagementMapper.selectDbQualificationManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            dbQualificationManagementMapper.deleteDbQualificationManagementByIds(ids);
        }
        
        // 遍历符合条件的考生，插入递补资格审查名单
        for (ScoreManagement score : scoreList)
        {
            try
            {
                // 创建递补资格审查名单对象
                DbQualificationManagement dbQualification = new DbQualificationManagement();
                
                // 复制考生信息
                dbQualification.setCandidateId(score.getCandidateId());
                dbQualification.setName(score.getName());
                dbQualification.setGender(score.getGender());
                dbQualification.setIdCard(score.getIdCard());
                dbQualification.setExamNumber(score.getExamNumber());
                dbQualification.setAdministrativeAptitudeScore(score.getAdministrativeAptitudeScore());
                dbQualification.setEssayScore(score.getEssayScore());
                dbQualification.setProfessionalSubjectScore(score.getProfessionalSubjectScore());
                dbQualification.setTotalScore(score.getTotalScore());
                dbQualification.setProfessionalSkillTestScore(score.getProfessionalSkillTestScore());
                dbQualification.setAppliedUnit(score.getAppliedUnit());
                dbQualification.setAppliedPosition(score.getAppliedPosition());
                dbQualification.setRecruitmentNumber(score.getRecruitmentNumber());
                dbQualification.setInterviewRatio(score.getInterviewRatio());
                dbQualification.setRanking(score.getRanking());
                dbQualification.setGraduationSchool(score.getGraduationSchool());
                dbQualification.setHasProfessionalSkillTest(score.getHasProfessionalSkillTest());
                dbQualification.setPositionCategory(score.getPositionCategory());
                dbQualification.setIsAlternate("Y");  // 设置为递补
//                dbQualification.setQualificationReviewResult("待审核");  // 默认为待审核
//                dbQualification.setIdentityVerificationResult("待验证");  // 默认为待验证
//                dbQualification.setPhysicalTestResult("待测评");  // 默认为待测评
//                dbQualification.setFinalResult("待确认");  // 默认为待确认
                
                // 执行插入操作
                dbQualificationManagementMapper.insertDbQualificationManagement(dbQualification);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("插入递补资格审查名单失败，准考证号：" + score.getExamNumber(), e);
            }
        }
        
        return successNum;
    }

    /**
     * 生成递补身份验证名单
     * 从递补资格审查名单中筛选出资格审查结果为"通过"的考生，生成递补身份验证名单
     * 
     * @param operName 操作用户
     * @return 生成的递补身份验证名单人数
     */
    @Override
    @Transactional
    public int generateDbIdentityList(String operName)
    {
        // 终审结果表
        resultManagementMapper.deleteAllResultManagement();

        // 递补体能测试表
        dbPhysicalManagementMapper.deleteAllDbPhysicalManagement();

        // 递补身份验证表
        dbIdentityManagementMapper.deleteAllIdentityManagement();

        // 递补资格审查表
        dbQualificationManagementMapper.deleteAllDbQualificationManagement();




        // 1. 获取所有成绩合格考生
        List<ScoreManagement> allScores = scoreManagementService.selectScoreManagementList(new ScoreManagement());

        // 获取资格审查不通过的考生职位
        QualificationManagement failedQualification = new QualificationManagement();
        failedQualification.setQualificationReviewResult("未通过");
        List<QualificationManagement> failedQualificationList = qualificationManagementMapper.selectQualificationManagementList(failedQualification);

        // 2. 获取递补资格审查不通过的考生
        DbQualificationManagement failedCriteria = new DbQualificationManagement();
        failedCriteria.setQualificationReviewResult("未通过");
        List<DbQualificationManagement> failedDBQualifications = dbQualificationManagementMapper.selectDbQualificationManagementList(failedCriteria);

        // 获取身份验证的考生
        IdentityManagement failedIdentityall = new IdentityManagement();
        List<IdentityManagement> failedListall = identityManagementMapper.selectIdentityManagementList(failedIdentityall);

        // 获取体能测评的考生
        PhysicalManagement failedPhysical = new PhysicalManagement();
        List<PhysicalManagement> failedPhysicalall = physicalManagementMapper.selectPhysicalManagementList(failedPhysical);

        // 3. 构建不通过考生标识集合（准考证号+身份证号）
        Set<String> failedDBQualificationsSet = new HashSet<>();
        for (DbQualificationManagement q : failedDBQualifications) {
            failedDBQualificationsSet.add(q.getExamNumber() + "_" + q.getIdCard());
        }

        Set<String> failedQualificationsSet = new HashSet<>();
        for (QualificationManagement q : failedQualificationList) {
            failedQualificationsSet.add(q.getExamNumber() + "_" + q.getIdCard());
        }

        Set<String> failedIdentitySet = new HashSet<>();
        for (IdentityManagement q : failedListall) {
            failedIdentitySet.add(q.getExamNumber() + "_" + q.getIdCard());
        }

        Set<String> failedPhysicalSet = new HashSet<>();
        for (PhysicalManagement q : failedPhysicalall) {
            failedPhysicalSet.add(q.getExamNumber() + "_" + q.getIdCard());
        }

        failedDBQualificationsSet.addAll(failedQualificationsSet);
        failedDBQualificationsSet.addAll(failedIdentitySet);
        failedDBQualificationsSet.addAll(failedPhysicalSet);


        // 4. 过滤有效考生
        List<ScoreManagement> validScores = allScores.stream()
                .filter(score -> !failedDBQualificationsSet.contains(score.getExamNumber() + "_" + score.getIdCard()))
                .collect(Collectors.toList());

        // 5. 按单位+职位分组处理
        Map<String, List<ScoreManagement>> grouped = validScores.stream()
                .collect(Collectors.groupingBy(s -> s.getAppliedUnit() + "_" + s.getAppliedPosition()));

        List<ScoreManagement> finalCandidates = new ArrayList<>();

        for (Map.Entry<String, List<ScoreManagement>> entry : grouped.entrySet()) {
            List<ScoreManagement> group = entry.getValue();
            if (group.isEmpty()) continue;

            // 6. 获取职位参数
            ScoreManagement sample = group.get(0);
            Long recruitment = sample.getRecruitmentNumber();
            String ratioStr = sample.getInterviewRatio();
            boolean hasSkillTest = "是".equals(sample.getHasProfessionalSkillTest());

            // 7. 解析面试比例
            int ratio = 3;
            try {
                String[] ratioParts = ratioStr.split(":");
                if (ratioParts.length == 2) {
                    ratio = Integer.parseInt(ratioParts[1]);
                }
            } catch (Exception e) {
                log.error("面试比例解析错误：{}", ratioStr, e);
            }

            // 8. 排序逻辑
            group.sort((a, b) -> {
                if (hasSkillTest) {
                    return b.getProfessionalSkillTestScore().compareTo(a.getProfessionalSkillTestScore());
                } else {
                    return b.getTotalScore().compareTo(a.getTotalScore());
                }
            });

            // 9. 计算应录取人数
            int required = recruitment.intValue() * ratio;
            int actualCount = Math.min(required, group.size());
            if (actualCount == 0) continue;

            // 10. 处理同分考生
            BigDecimal baseScore = hasSkillTest ?
                    group.get(actualCount-1).getProfessionalSkillTestScore() :
                    group.get(actualCount-1).getTotalScore();

            for (int i = actualCount; i < group.size(); i++) {
                BigDecimal current = hasSkillTest ?
                        group.get(i).getProfessionalSkillTestScore() :
                        group.get(i).getTotalScore();

                if (current.compareTo(baseScore) == 0) {
                    actualCount++;
                } else {
                    break;
                }
            }

            // 11. 添加最终名单
            finalCandidates.addAll(group.subList(0, Math.min(actualCount, group.size())));
        }

        // 12. 转换为递补资格审查对象并插入
        return dbIdentityManagementService.insertDbIdentityListFromScore(finalCandidates, operName);
    }

    /**
     * 获取四级联考递补资格审查统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getDbQualificationStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有递补资格审查数据
        List<DbQualificationManagement> dbQualificationList = dbQualificationManagementMapper.selectDbQualificationManagementList(new DbQualificationManagement());
        
        // 总数
        int total = dbQualificationList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (DbQualificationManagement dbQualification : dbQualificationList)
        {
            // 统计通过人数
            if ("通过".equals(dbQualification.getQualificationReviewResult()))
            {
                passed++;
            }
            
            // 统计职位分布
            String position = dbQualification.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
